import 'package:flutter/material.dart';

import '../../service/news_request.dart';
import './news_model.dart';

class HomePageViewModel {
  List<NewsModel> topStories = [];
  List<NewsListModel> stories = [];

  Future<void> fetchLastest() async {
    var map = await NewsRequest.shared.fetchLastest();
    if (map.containsKey('top_stories')) {
      var topList = map['top_stories'];
      if (topList is List<dynamic>) {
        topStories = topList.map((data) => NewsModel.fromMap(data)).toList();
      }
    }

    List<NewsModel> news = [];
    if (map.containsKey('stories')) {
      var list = map['stories'];
      if (list is List<dynamic>) {
        news = list.map((data) => NewsModel.fromMap(data)).toList();
      }
    }

    if (map.containsKey('date')) {
      String dateString = map['date'];
      stories.add(NewsListModel(dateString: dateString, news: news));
    }
  }

  Future<void> fetchBefore() async {
    String dateString = stories.last.dateString;
    debugPrint(dateString);
    var map = await NewsRequest.shared.fetchBefore(dateString: dateString);
    List<NewsModel> news = [];
    if (map.containsKey('stories')) {
      var list = map['stories'];
      if (list is List<dynamic>) {
        news = list.map((data) => NewsModel.fromMap(data)).toList();
      }
    }

    if (map.containsKey('date')) {
      String dateString = map['date'];
      stories.add(NewsListModel(dateString: dateString, news: news));
    }
  }
}
